<template>
    <div style='width:400px'>
        <a-form ref='formRef' autocomplete='off' :rules='rules' :model='formData' layout='vertical' @finish='submit'>
            <a-form-item label='新密码' name='new_pw'>
                <a-input-password size='large' v-model:value='formData.new_pw' type='password' />
            </a-form-item>
            <a-form-item label='重复新密码' name='again'>
                <a-input-password size='large' v-model:value='formData.again' type='password' />
            </a-form-item>
            <a-form-item>
                <a-button size='large' type='primary' html-type='submit' :loading='loading'>保 存</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from "@vue/reactivity";
import { safetySettingApi } from '@/api/user'
import { message } from "ant-design-vue";
import { useStore } from "vuex";

    const formData = reactive({
        new_pw : '',
        again : ''
    })

    const loading = ref(false)
    const formRef = ref();
    
    const rules = {
      new_pw: [{ required: true, validator: (_rule, value: string) => {
            if (value === '') {
                return Promise.reject('请填写新的登录密码');
            }

            if(value.length < 6) {
                return Promise.reject('密码长度最少6位');
            }

            return Promise.resolve();


      }, trigger: 'change' }],
      again: [{ required: true, validator: (_rule, value: string) => {
            if (value === '') {
                return Promise.reject('请重复新密码');
            }

            if(value !== formData.new_pw) {
                return Promise.reject('密码不一致');
            }

            return Promise.resolve();


      }, trigger: 'change' }],
    }
    

    async function submit() {
        loading.value = true
        const res = await safetySettingApi(formData)
        loading.value = false
        if(res.success) {
            message.success('更新成功')
            formRef.value.resetFields()
        }else {
            message.error(res.message)
        }

    }

</script>
